package com.ht.pms.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ht.pms.core.common.constant.SalaryConstants;
import com.ht.pms.core.common.exception.ServiceException;
import com.ht.pms.core.config.ExecutorPool;
import com.ht.pms.core.dao.SalaryEmailDao;
import com.ht.pms.core.dao.sql.SqlAssembleTemp;
import com.ht.pms.core.dto.NoticeEmailRecord;
import com.ht.pms.core.dto.dict.DictParamsDto;
import com.ht.pms.core.dto.send.*;
import com.ht.pms.core.dto.upload.UpLoadTemp;
import com.ht.pms.core.feign.EipoutFeign;
import com.ht.pms.core.feign.GatewayFeign;
import com.ht.pms.core.service.NoticeEmailRecordService;
import com.ht.pms.core.service.SalaryEmailService;
import com.ht.pms.core.service.email.SendEmail;
import com.ht.pms.core.service.job.ThreadManager;
import com.ht.ussp.core.Result;
import com.ht.ussp.util.DateUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class SalaryEmailServiceImpl implements SalaryEmailService {
    private static final Logger LOG = LoggerFactory.getLogger(SalaryEmailServiceImpl.class);

    @Autowired
    private SendEmail sendEmail;

    @Autowired
    private SalaryEmailDao salaryEmailDao;

    @Autowired
    private SqlAssembleTemp sqlAssembleTemp;

    @Autowired
    private EipoutFeign eipoutFeign;

    @Value("${pms.send.htmlurl}")
    private String sendHtmlUrl;

    @Value("${pms.send.time}")
    private int tokenTime;

    @Autowired
    private GatewayFeign gatewayFeign;

    @Autowired
    private ThreadManager threadManager;

    @Value("${pms.send.sleep.time}")
    private int sleepTime;

    @Autowired
    private ContactPerson contactPerson;

    @Autowired
    private NoticeEmailRecordService noticeEmailRecordService;

    @Override
    public void sendSalaryEmail(SendSalaryReq dto) throws Exception {
        LOG.info("=============>>>>>>>>>发送邮件开始");
        Long start = System.currentTimeMillis();
        String batchCode = dto.getBatchCode();
        String tableName = null;
        int flag = Integer.parseInt(dto.getFlag());
        int sendType = Integer.parseInt(dto.getSendType());
        int type = 1; //邮件

        List<NoticeSendDto> noticeSendList = null;
        if (flag == 1) { //全部发送
            List<SendBaseDto> sendAllBase = null;

            if (sendType == 1) { //考勤
                tableName = SalaryConstants.SALARY_FIELD_TABLE_A;
                sendAllBase = salaryEmailDao.findAllSalaryBase(batchCode, tableName);
            } else if (sendType == 2) { //工资
                tableName = SalaryConstants.SALARY_FIELD_TABLE_B;
                sendAllBase = salaryEmailDao.findAllSalaryBase(batchCode, tableName);
            }
            if (sendAllBase == null || sendAllBase.size() == 0) {
                throw new ServiceException("sendSalaryEmail", "没有可发送的数据，请导入有效数据或进行全部撤回");
            }

            dto.setSendBaseList(sendAllBase);
        } else if (flag == 2) {
            if ( !"1".equals(dto.getIsFailRetry()) && (dto.getSendBaseList() == null || dto.getSendBaseList().size() == 0)) {
                throw new ServiceException("sendSalaryEmail", "缺少必要发送参数");

            } else {
                if("1".equals(dto.getIsFailRetry())){
                    List<SendBaseDto> sendBaseDtoList = new ArrayList<>();
                    //失败重发
                    List<NoticeEmailRecord> emailRecords = noticeEmailRecordService.selectList(new EntityWrapper<NoticeEmailRecord>().eq("batch_code",batchCode).eq("send_type",dto.getSendType()).eq("send_state","1"));
                    if(CollectionUtils.isEmpty(emailRecords)){
                        throw new ServiceException("sendSalaryEmail", "缺少必要发送参数");
                    }
                    for (NoticeEmailRecord emailRecord:emailRecords) {
                        SendBaseDto sendBaseDto = new SendBaseDto();
                        sendBaseDto.setJobCode(emailRecord.getJobCode());
                        sendBaseDtoList.add(sendBaseDto);
                    }
                    dto.setSendBaseList(sendBaseDtoList);
                }
                List<String> jobCode = new ArrayList<>();
                List<SendBaseDto> sendParamList = dto.getSendBaseList();
                for (SendBaseDto sendBaseDto : sendParamList) {
                    jobCode.add(sendBaseDto.getJobCode());
                }
                if (!CollectionUtils.isEmpty(jobCode)) {
                    List<SendBaseDto> singleList = null;

                    if (sendType == 1) { //考勤
                        tableName = SalaryConstants.SALARY_FIELD_TABLE_A;
                        singleList = salaryEmailDao.findOneSalaryEmail(jobCode, batchCode, tableName);
                    } else if (sendType == 2) { //工资
                        tableName = SalaryConstants.SALARY_FIELD_TABLE_B;
                        singleList = salaryEmailDao.findOneSalaryEmail(jobCode, batchCode, tableName);
                    }

                    dto.setSendBaseList(singleList);
                }

            }
        }
        String typeName = null;
        if (sendType == 1) { //考勤
            typeName = "考勤";
        } else if (sendType == 2) {
            typeName = "工资";
        }


        String subjectTitle = "";
        StringBuilder sb = new StringBuilder();

        List<UpLoadTemp> upLoadTempList = salaryEmailDao.queryUploadTemp(batchCode);
        if (!CollectionUtils.isEmpty(upLoadTempList)) {
            UpLoadTemp upLoadTemp = upLoadTempList.get(0);
            String time = upLoadTemp.getTime();
            if (!StringUtils.isBlank(time)) {
                String[] arr = time.split("-");
                String timeStr = arr[0] + "年" + arr[1] + "月";

                subjectTitle = timeStr + typeName + "邮件";


                sb.append("<p>亲爱的小伙伴:</p>");
                sb.append("<p>以下是您" + timeStr + typeName + "明细,请点击下面的按钮查看</p>");
                sb.append("<p><a style='padding: 10 100px;background:#35AD37;color:#ffffff;border-radius: 5px;font-size: 16px;text-decoration:none;' href='%s' rel='external'>查看" + typeName + "</a></p>");
                sb.append("<p>若按钮无效，请复制下方链接到浏览器地址栏进行访问：</p>");
                sb.append("<p style='color:#35AD37;'>%s</p>");
                sb.append("<p style='color:#c3c3c3;font-size:12px'>此邮件为系统自动发送，请勿直接回复。</p>");

            }

            List<SendBaseDto> sendBaseList = dto.getSendBaseList();

            if (!CollectionUtils.isEmpty(sendBaseList)) {
                SendGroupTempDto sendGroupTempDto = new SendGroupTempDto();
                sendGroupTempDto.setTime(time);
                sendGroupTempDto.setTableName(tableName);
                sendGroupTempDto.setSendType(sendType);
                sendGroupTempDto.setEmailContent(sb.toString());
                sendGroupTempDto.setBatchCode(batchCode);
                sendGroupTempDto.setSubjectTitle(subjectTitle);
                sendGroupTempDto.setType(type);
                sendGroupTempDto.setEmailType(dto.getEmailType());

                groupSendEmail(sendBaseList, sendGroupTempDto);
            }


            if (flag == 1) {
                NoticeSendDto noticeSendDto = new NoticeSendDto();
                noticeSendDto.setBatchCode(batchCode);
                noticeSendDto.setSendType(sendType);
                noticeSendDto.setSendServer(1); //邮件
                salaryEmailDao.saveNoticeSendDto(noticeSendDto);
            }

        }
        Long end = System.currentTimeMillis();

        LOG.info("=============>>>>>>>>>发送邮件结束,用时{}", end - start);
    }


    public void groupSendEmail(List<SendBaseDto> sendBaseList, SendGroupTempDto sendGroupTempDto) {
        int allSize = sendBaseList.size(); //209
        Double countThread = 10.0;
        Double size = allSize / countThread;
        int averSize = (int) Math.ceil(size); // 10

        for (int threadCount = 0; threadCount < countThread; threadCount++) {
            int lower = threadCount * averSize;
            int upper = (threadCount == countThread - 1) ? allSize : lower + averSize;
            int threadNumber = threadCount;

            if (upper < allSize || upper == allSize) {
                LOG.info("=============>>>>>>>>>发送邮件开始lower=" + lower);
                LOG.info("=============>>>>>>>>>发送邮件开始upper=" + upper);
                LOG.info("=============>>>>>>>>>发送邮件开始threadNumber=" + threadNumber);
                 ExecutorPool.cachedThreadPool.execute(
                        new Runnable() {
                            @Override
                            public void run() {
                                for (int i = lower; i < upper; i++) {
                                    try {
                                        Thread.sleep(sleepTime);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                        LOG.info("睡眠线程出错{}", e);
                                    }
                                    sendEmailAsync(sendBaseList.get(i), sendGroupTempDto, threadNumber);
                                }
                            }
                        });
            }
        }


    }


    @Transactional(rollbackFor = Exception.class)
    public void sendEmailAsync(SendBaseDto sendBaseDto, SendGroupTempDto sendGroupTempDto, int threadNumber) {
        LOG.info("============>>>>>>发送邮件开始threadName=" + Thread.currentThread().getName());
        Long start = System.currentTimeMillis();
        TreeSet<String> to = new TreeSet<>();
        String jobCode = sendBaseDto.getJobCode();
        String batchCode = sendGroupTempDto.getBatchCode();
        int sendType = sendGroupTempDto.getSendType();
        MailReqDto email = new MailReqDto();
        String emailContent = sendGroupTempDto.getEmailContent();
        String tableName = sendGroupTempDto.getTableName();
        String time = sendGroupTempDto.getTime();
        Integer id = sendBaseDto.getId();
        Integer type = sendGroupTempDto.getType();
        String emailType = sendGroupTempDto.getEmailType();

        Map<String, String> urlMap = createAccessUrl(jobCode, batchCode, sendType, type);
        String url = urlMap.get("url");
        String token = urlMap.get("token");
        to.add(sendBaseDto.getEmail());
        email.setSubject(sendGroupTempDto.getSubjectTitle());
        email.setText(String.format(emailContent, url, url));
        email.setTo(to);
        LOG.info("=============>>>>>邮件内容:" + email);

        String emailAddr = sendBaseDto.getEmail();

        int sendState = 0;
        Result result = sendEmail(threadNumber, email, emailAddr);


        LOG.info("===============>>>>>>>eip返回内容result=" + result);
        boolean isFirst = true;
        if (result.getReturnCode().equals("0000")) {
            //发送成功，更新状态
            isFirst = successProcess(jobCode, batchCode, sendType, tableName, id, emailType,isFirst);
        } else {
            //发送成功，重试三次
            for (int i=1;i<=3;i++) {
                result = sendEmail(RandomUtils.nextInt(10),email,emailAddr);
                if("0000".equals(result.getReturnCode())){
                    //成功便退出循环，更新成功状态
                    isFirst = successProcess(jobCode, batchCode, sendType, tableName, id, emailType,isFirst);
                    break;
                }
            }
            //退出循环和还是失败，更新失败状态
            if(!"0000".equals(result.getReturnCode())){
                sendState = 1;//发送失败
                salaryEmailDao.updateRecordSendStateById(tableName, id, 2,emailType);
            }

        }

        //保存 核对时间及发送记录
        NoticeEmailRecordDto noticeRecordSend = new NoticeEmailRecordDto();
        noticeRecordSend.setBatchCode(batchCode);
        noticeRecordSend.setJobCode(jobCode);
        noticeRecordSend.setSendType(sendType);
        noticeRecordSend.setName(sendBaseDto.getName());
        noticeRecordSend.setSendState(sendState);
        noticeRecordSend.setSendCode(token);
        noticeRecordSend.setSendYm(time);
        if(isFirst){
            salaryEmailDao.saveSendLog(noticeRecordSend);
        }


        Long times = System.currentTimeMillis() - start;

        LOG.info("============>>>>>>发送邮件结束 邮箱 emailTo=" + to + ",time=" + times);
    }

    private boolean successProcess(String jobCode, String batchCode, int sendType, String tableName, Integer id, String emailType,boolean isFirst) {
        List<NoticeEmailRecordDto> recordSendList = salaryEmailDao.findNoticRecordSend(batchCode, jobCode, sendType);
        if (!CollectionUtils.isEmpty(recordSendList)) {
            isFirst = false;
            for (NoticeEmailRecordDto noticeRecordSend : recordSendList) { //把有效改为无效
                salaryEmailDao.updateNoticeRecordIsUsable(noticeRecordSend);
            }
        }
        salaryEmailDao.updateRecordSendStateById(tableName, id, 1,emailType);
        return isFirst;
    }

    private Result sendEmail(int threadNumber, MailReqDto email, String emailAddr) {
        Result result = null;
        switch (threadNumber) {
            case 0:
                if(emailAddr.contains("hongte")){
                    result = eipoutFeign.sendEmailNew1(email);
                }else {
                    result = chooseSendEmail(emailAddr,email);
                }
                break;
            case 1:
                if(emailAddr.contains("hongte")){
                    result = eipoutFeign.sendEmailNew2(email);
                }else {
                    result = chooseSendEmail(emailAddr,email);
                }
                break;
            case 2:
                if(emailAddr.contains("hongte")){
                    result = eipoutFeign.sendEmailNew3(email);
                }else {
                    result = chooseSendEmail(emailAddr,email);
                }
                break;
            case 3:
                if(emailAddr.contains("hongte")){
                    result = eipoutFeign.sendEmailNew4(email);
                }else {
                    result = chooseSendEmail(emailAddr,email);
                }
                break;
            case 4:
                if(emailAddr.contains("hongte")){
                    result = eipoutFeign.sendEmailNew5(email);
                }else {
                    result = chooseSendEmail(emailAddr,email);
                }
                break;
            case 5:
                if(emailAddr.contains("hongte")){
                    result = eipoutFeign.sendEmailNew6(email);
                }else {
                    result = chooseSendEmail(emailAddr,email);
                }
                break;
            case 6:
                if(emailAddr.contains("hongte")){
                    result = eipoutFeign.sendEmailNew7(email);
                }else {
                    result = chooseSendEmail(emailAddr,email);
                }
                break;
            case 7:
                if(emailAddr.contains("hongte")){
                    result = eipoutFeign.sendEmailNew8(email);
                }else {
                    result = chooseSendEmail(emailAddr,email);
                }
                break;
            case 8:
                if(emailAddr.contains("hongte")){
                    result = eipoutFeign.sendEmailNew9(email);
                }else {
                    result = chooseSendEmail(emailAddr,email);
                }
                break;
            case 9:
                if(emailAddr.contains("hongte")){
                    result = eipoutFeign.sendEmailNew10(email);
                }else {
                    result = chooseSendEmail(emailAddr,email);
                }
                break;
        }
        return result;
    }

    public Result chooseSendEmail(String email,MailReqDto dto){
        Result result = null;
        if(email.contains("zhichengdanbao")){
            result = eipoutFeign.sendEmailNewZc(dto);
        }else if(email.contains("tiandalianhe")){
            result = eipoutFeign.sendEmailNewTd(dto);
        }else if(email.contains("lianshengdanbao")){
            int num = RandomUtils.nextInt(3)+1;
            switch (num){
                case 1:
                    result = eipoutFeign.sendEmailNewLs1(dto);
                    break;
                case 2:
                    result = eipoutFeign.sendEmailNewLs2(dto);
                    break;
                case 3:
                    result = eipoutFeign.sendEmailNewLs3(dto);
                    break;
                    default:
            }
        }else if(email.contains("fuchengzichan")){
            int num = RandomUtils.nextInt(2)+1;
            switch (num){
                case 1:
                    result = eipoutFeign.sendEmailNewFc1(dto);
                    break;
                case 2:
                    result = eipoutFeign.sendEmailNewFc2(dto);
                    break;

                default:
            }
        }else if (email.contains("xianzhiqin")){
            result = eipoutFeign.sendEmailNewZq(dto);
        }
        return result;
    }

//    public Result eipSendEmail(MailReqDto email, int threadNumber) {
//        Result result = switchSendEmail(email, threadNumber);
//        if (result != null) {
//            if (!result.getReturnCode().equals("0000")) {
//                try {
//                    Thread.sleep(sleepTime);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                    LOG.info("睡眠线程出错{}", e);
//                }
//                result = switchSendEmail(email, threadNumber);
//            }
//        }
//
//        return result;
//    }

//    public Result switchSendEmail(MailReqDto email, int threadNumber) {
//        Result result = null;
//        LOG.info("=============>>>>>case:" + email);
//        switch (threadNumber) {
//            case 0:
//                result = eipoutFeign.sendEmailNew1(email);
//                break;
//            case 1:
//                result = eipoutFeign.sendEmailNew2(email);
//                break;
//            case 2:
//                result = eipoutFeign.sendEmailNew3(email);
//                break;
//            case 3:
//                result = eipoutFeign.sendEmailNew4(email);
//                break;
//            case 4:
//                result = eipoutFeign.sendEmailNew5(email);
//                break;
//            case 5:
//                result = eipoutFeign.sendEmailNew6(email);
//                break;
//            case 6:
//                result = eipoutFeign.sendEmailNew7(email);
//                break;
//            case 7:
//                result = eipoutFeign.sendEmailNew8(email);
//                break;
//            case 8:
//                result = eipoutFeign.sendEmailNew9(email);
//                break;
//            case 9:
//                result = eipoutFeign.sendEmailNew10(email);
//                break;
//        }
//        return result;
//    }

    public Map<String, String> createAccessUrl(String jobCode, String batchCode, int sendType, int type) {
        Map<String, String> paramap = new HashMap<>();
        String url = null;
        String token = null;
        String gateWayResult = gatewayFeign.createSalaryToken(jobCode, batchCode, sendType, tokenTime, type);
        if (gateWayResult != null) {
            JSONObject uaaResult = JSON.parseObject(gateWayResult);
            if (uaaResult.get("status_code").equals("0000")) {
                JSONObject resultJson = uaaResult.getJSONObject("result");
                token = resultJson.getString("token");
            }
        }

        if (token != null) {
            if (sendType == 1) { //考勤
                url = sendHtmlUrl + "/salarySend/workTimeCheck?code=" + token;
            } else if (sendType == 2) { //工资
                url = sendHtmlUrl + "/salarySend/salaryEmailCheck?code=" + token;
            }
        }
        paramap.put("url", url);
        paramap.put("token", token);
        return paramap;
    }

    @Override
    public void updateEndTime(String batchCode, String endTime) throws Exception {
        salaryEmailDao.updateEndTime(batchCode, endTime);
    }


    @Override
    public Map<String, Object> createSendSalaryData(String code) throws Exception {
        Map<String, Object> map = new HashMap<>();
        int templateType = 0;
        String jobCode = null;
        String batchCode = null;
        Integer sendType = null;
        Integer state = 0;  //0有效 1无效
        Integer type = 1;  //1.邮件 2.钉钉
        String sdTime = "";
        String gateWayResult = gatewayFeign.validateSalayJwt("Bearer " + code);
        LOG.info("======>>>>>uaa返回{}",gateWayResult);
        if (gateWayResult != null) {
            JSONObject uaaResult = JSON.parseObject(gateWayResult);
            if (uaaResult.get("status_code").equals("0000")) {
                JSONObject resultJson = uaaResult.getJSONObject("result");
                jobCode = resultJson.getString("jobNumber");
                batchCode = resultJson.getString("batchNumber");
                sendType = resultJson.getInteger("sendType");
                type = resultJson.getInteger("type");

//                List<SalaryAccessDto> salaryList = salaryEmailDao.queryAccessSend(jobCode, batchCode, sendType, code, type);
//                LOG.info("======>>>>>存不存在code{}",salaryList);

                List<SendSalaryTimeDto> sendSalaryTimeList = salaryEmailDao.querySalaryTime(batchCode, sendType);
                LOG.info("======>>>>>发送时间查询返回{}",sendSalaryTimeList);
                if (!CollectionUtils.isEmpty(sendSalaryTimeList)) {
                    SendSalaryTimeDto sendSalaryTimeDto = sendSalaryTimeList.get(0);
                    String time = sendSalaryTimeDto.getTime();
                    String checkEndTime = sendSalaryTimeDto.getCheckEndTime();
                    if (!StringUtils.isBlank(time)) {
                        String[] arr = time.split("-");
                        sdTime = time;
                        String timeStr = arr[0] + "年" + arr[1] + "月";
                        map.put("timeStr", timeStr);
                    }
                    if (!StringUtils.isBlank(checkEndTime)) {
//                            String[] arrYear = checkEndTime.split(" ");
//                            String[] arr = arrYear[0].split("-");
//                            String timeStr = arr[1] + "月" + arr[2] + "日";

                        map.put("checkTime", checkEndTime);
                    }
                }

                //判断是否第一次发送邮件
                if(sendType == 2){
                    Map<String,Object> result = salaryEmailDao.isFirstSendEmail(jobCode,batchCode);
                    String emailType = result.get("email_type")+"";
                    map.put("emailType",emailType);
                }

                salaryEmailDao.confirmSalaryData(sendType, batchCode, jobCode,type);
                Integer titleType = null ;
                String contactName = "";
                String otherInfo = "";
                List<SendSalaryDataDto> salaryDataList = createSalaryData(sendType, batchCode, jobCode);
                if(!CollectionUtils.isEmpty(salaryDataList)){
                    for (SendSalaryDataDto dataDto:salaryDataList) {
                        if(dataDto.getDictName().equals("邮箱")){
                            String email = dataDto.getDictData()+"";
                            if(email.contains("zhichengdanbao")){
                                titleType = 1;
                                contactName = contactPerson.getContractName(sendType,1);
                                otherInfo = contactPerson.getOtherInfo();
                            }else if(email.contains("tiandalianhe")){
                                titleType = 2;
                                contactName = contactPerson.getContractName(sendType,2);
                                otherInfo = contactPerson.getOtherInfo();
                            }else if(email.contains("lianshengdanbao")){
                                titleType = 3;
                                contactName = contactPerson.getContractName(sendType,3);
                                otherInfo = contactPerson.getOtherInfo();
                            }else if(email.contains("fuchengzichan")){
                                titleType = 4;
                                contactName = contactPerson.getContractName(sendType,4);
                                otherInfo = contactPerson.getOtherInfo();
                            }else if(email.contains("xianzhiqin")){
                                titleType = 6;
                                contactName = contactPerson.getContractName(sendType,6);
                                otherInfo = contactPerson.getOtherInfo();
                            }else if(email.contains("chequancar")) {
                                titleType = 7;
                                contactName = contactPerson.getContractName(sendType,7);
                                otherInfo = contactPerson.getOtherInfo();
                            } else {
                                titleType = 5;
                                contactName = contactPerson.getContractName(sendType,5);
                                otherInfo = contactPerson.getOtherInfo();
                            }
                        }
                    }
                }
                map.put("otherInfo",otherInfo);
                map.put("contactName",contactName);
                map.put("sendType",sendType);
                map.put("titleType",titleType);
                LOG.info("======>>>>>查询数据返回{}",salaryDataList);
                map.put("salaryData", salaryDataList);



            } else {
                state = 1;
            }
        }

        map.put("salaryState", state);

        return map;
    }

//    @Override
//    public SalaryAccessDto accessSendEmail(String code, String sendType) {
//
//        String jobCode = null;
//        String batchCode = null;
//        String gateWayResult = gatewayFeign.validateSalayJwt("Bearer " + code);
//        if (gateWayResult != null) {
//            JSONObject uaaResult = JSON.parseObject(gateWayResult);
//            if (uaaResult.get("status_code").equals("0000")) {
//                JSONObject resultJson = uaaResult.getJSONObject("result");
//                jobCode = resultJson.getString("jobNumber");
//                batchCode = resultJson.getString("batchNumber");
//            }
//        }
//        List<SalaryAccessDto> salaryList = salaryEmailDao.queryAccessSend(jobCode, batchCode, Integer.parseInt(sendType), code);
//        SalaryAccessDto salaryAccessDto = null;
//
//        if (!CollectionUtils.isEmpty(salaryList)) {
//            salaryAccessDto = salaryList.get(0);
//            salaryAccessDto.setState("0");
//        } else {
//            salaryAccessDto = new SalaryAccessDto();
//            salaryAccessDto.setState("1");
//        }
//        return salaryAccessDto;
//    }

    @Override
    public Map<String, Object> createSendSalaryDataInner(String jobCode, String batchCode, int sendType) throws Exception {
        Map<String, Object> map = new HashMap<>();
        int templateType = 0;
              List<SendSalaryTimeDto> sendSalaryTimeList = salaryEmailDao.querySalaryTime(batchCode, sendType);
        if (!CollectionUtils.isEmpty(sendSalaryTimeList)) {
            SendSalaryTimeDto sendSalaryTimeDto = sendSalaryTimeList.get(0);
            String time = sendSalaryTimeDto.getTime();
            String checkEndTime = sendSalaryTimeDto.getCheckEndTime();
            if (!StringUtils.isBlank(time)) {
                String[] arr = time.split("-");
                String timeStr = arr[0] + "年" + arr[1] + "月";
                map.put("timeStr", timeStr);
            }
            if (!StringUtils.isBlank(checkEndTime)) {
//                String[] arrYear = checkEndTime.split(" ");
//                String[] arr = arrYear[0].split("-");
//                String timeStr = arr[1] + "月" + arr[2] + "日";

                map.put("checkTime", checkEndTime);
            }
        }
//        if (sendType == 1) {//考勤
//            templateType = 4;
//        } else if (sendType == 2) {//工资
//            templateType = 5;
//        }

        Integer titleType = null ;
        String contactName = "";
        String otherInfo = "";
        List<SendSalaryDataDto> salaryDataList = createSalaryData(sendType, batchCode, jobCode);
        if(!CollectionUtils.isEmpty(salaryDataList)){
            for (SendSalaryDataDto dataDto:salaryDataList) {
                if(dataDto.getDictName().equals("邮箱")){
                    String email = dataDto.getDictData()+"";
                    if(email.contains("zhichengdanbao")){
                        titleType = 1;
                        contactName = contactPerson.getContractName(sendType,1);
                        otherInfo = contactPerson.getOtherInfo();
                    }else if(email.contains("tiandalianhe")){
                        titleType = 2;
                        contactName = contactPerson.getContractName(sendType,2);
                        otherInfo = contactPerson.getOtherInfo();
                    }else if(email.contains("lianshengdanbao")){
                        titleType = 3;
                        contactName = contactPerson.getContractName(sendType,3);
                        otherInfo = contactPerson.getOtherInfo();
                    }else if(email.contains("fuchengzichan")){
                        titleType = 4;
                        contactName = contactPerson.getContractName(sendType,4);
                        otherInfo = contactPerson.getOtherInfo();
                    }else if(email.contains("xianzhiqin")){
                        titleType = 6;
                        contactName = contactPerson.getContractName(sendType,6);
                        otherInfo = contactPerson.getOtherInfo();
                    }else if(email.contains("chequancar")){
                        titleType = 7;
                        contactName = contactPerson.getContractName(sendType,7);
                        otherInfo = contactPerson.getOtherInfo();
                    }else {
                        titleType = 5;
                        contactName = contactPerson.getContractName(sendType,5);
                        otherInfo = contactPerson.getOtherInfo();
                    }
                }
            }
        }
        map.put("otherInfo",otherInfo);
        map.put("contactName",contactName);
        map.put("titleType",titleType);
        map.put("salaryData", salaryDataList);
        return map;
    }

    @Override
    public void sendRecall(String type, String jobCode, String batchCode, int sendType) throws Exception {
        //type 1批量 2单个
        int itype = Integer.parseInt(type);
        String tableName = null;
        if (sendType == 1) {
            tableName = SalaryConstants.SALARY_FIELD_TABLE_A;

        } else if (sendType == 2) {
            tableName = SalaryConstants.SALARY_FIELD_TABLE_B;
        }

        List<NoticeSendDto> noticeSendList = salaryEmailDao.findNoticeSendList(batchCode, sendType);
        if (noticeSendList.size() > 0) {
            if (itype == 1) {
                salaryEmailDao.sendRecall(batchCode, sendType);
                salaryEmailDao.updateNoticeIsUsableAll(batchCode, sendType);
                salaryEmailDao.updateRecordSendState(tableName, batchCode, null, 3); //撤回
            } else if (itype == 2) {
                salaryEmailDao.updateNoticeIsUsable(batchCode, jobCode, sendType);
                salaryEmailDao.updateRecordSendState(tableName, batchCode, jobCode, 3); //撤回
            }

        } else {
            throw new ServiceException("sendRecall", "请先进行发送");
        }


    }

    @Override
    public CountSendNumberDto countSendNumber(String batchCode) throws Exception {
        int countNumber = 0;
        int preSendNumber = 0; //未发送
        int sendedNumber = 0; //已发送
        int callNumber = 0;  //撤回
        int failNumber = 0;  //失败
        int dpreSendNumber = 0;
        int dsendedNumber = 0;
        int dcallNumber = 0;
        int dfailNumber = 0;
        CountSendNumberDto countSendNumberDto = new CountSendNumberDto();
        if (!StringUtils.isBlank(batchCode)) {
            List<NoticeEmailRecordDto> batchCodeList = salaryEmailDao.findBatchCode(batchCode);


            String tableName = null;
            if (batchCodeList != null && batchCodeList.size() > 0) {
                NoticeEmailRecordDto noticeEmailRecordDto = batchCodeList.get(0);
                batchCode = noticeEmailRecordDto.getBatchCode();
                if (noticeEmailRecordDto.getSendType().equals(1)) { //考勤
                    tableName = SalaryConstants.SALARY_FIELD_TABLE_A;
                } else if (noticeEmailRecordDto.getSendType().equals(2)) {
                    tableName = SalaryConstants.SALARY_FIELD_TABLE_B;
                }
                if (tableName != null) {
                    List<SendDataCountVo> list = salaryEmailDao.selectSendData(batchCode, tableName);
                    if (!CollectionUtils.isEmpty(list)) {
                        countNumber = list.size();
                        for (SendDataCountVo sendDataCountVo : list) {
                            //邮件发送状态统计
                            if (sendDataCountVo.getSendState() == 0) { //发送状态 0 未发送 1 已发送 2 发送失败 3 撤回'
                                preSendNumber += 1;
                            } else if (sendDataCountVo.getSendState() == 1) {
                                sendedNumber += 1;
                            } else if (sendDataCountVo.getSendState() == 2) {
                                failNumber += 1;
                            } else if (sendDataCountVo.getSendState() == 3) {
                                callNumber += 1;
                            }
                            //钉钉发送状态统计
                            if (sendDataCountVo.getDdState() == 0) { //发送状态 0 未发送 1 已发送 2 发送失败 3 撤回'
                                dpreSendNumber += 1;
                            } else if (sendDataCountVo.getDdState() == 1) {
                                dsendedNumber += 1;
                            } else if (sendDataCountVo.getDdState() == 2) {
                                dfailNumber += 1;
                            } else if (sendDataCountVo.getDdState() == 3) {
                                dcallNumber += 1;
                            }


                        }
                    }
                }

            }


        }
        //总记录数
        countSendNumberDto.setCountNumber(countNumber);
        countSendNumberDto.setPreSendNumber(preSendNumber);
        countSendNumberDto.setSendedNumber(sendedNumber);
        countSendNumberDto.setFailNumber(failNumber);
        countSendNumberDto.setCallNumber(callNumber);
        countSendNumberDto.setDpreSendNumber(dpreSendNumber);
        countSendNumberDto.setDsendedNumber(dsendedNumber);
        countSendNumberDto.setDfailNumber(dfailNumber);
        countSendNumberDto.setDcallNumber(dcallNumber);
        return countSendNumberDto;
    }


    public List<SendSalaryDataDto> createSalaryData(int templateType, String batchCode, String jobCode) {
        List<SendSalaryDataDto> dataList = new ArrayList<>();
        List<DictParamsDto> dictList = salaryEmailDao.queryEamilTemplate(templateType); //工资
        if (!CollectionUtils.isEmpty(dictList)) {
            if (!StringUtils.isBlank(batchCode) && !StringUtils.isBlank(jobCode)) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("audit_state", 1);
                paramMap.put("in_state", 1);
                paramMap.put("batch_code", batchCode);
                paramMap.put("job_code", jobCode);
                String sql = sqlAssembleTemp.assembleQuery(dictList, paramMap);
                System.out.println(sql);
                Map<String, Object> resultMap = salaryEmailDao.createSendSalaryData(sql);
                if (!MapUtils.isEmpty(resultMap)) {

                    for (DictParamsDto dictParamsDto : dictList) {
                        SendSalaryDataDto sendSalaryDataDto = new SendSalaryDataDto();
                        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
                            if (dictParamsDto.getDictCode().equals(entry.getKey())) {
                                sendSalaryDataDto.setDictName(dictParamsDto.getDictName());
                                sendSalaryDataDto.setDictData(entry.getValue());
                                sendSalaryDataDto.setIsTop(dictParamsDto.getIsTop());
                                dataList.add(sendSalaryDataDto);
                            }
                        }
                    }
                } else {
                    for (DictParamsDto dictParamsDto : dictList) {
                        SendSalaryDataDto sendSalaryDataDto = new SendSalaryDataDto();
                        sendSalaryDataDto.setDictName(dictParamsDto.getDictName());
                        dataList.add(sendSalaryDataDto);
                    }
                }
            } else {
                for (DictParamsDto dictParamsDto : dictList) {
                    SendSalaryDataDto sendSalaryDataDto = new SendSalaryDataDto();
                    sendSalaryDataDto.setDictName(dictParamsDto.getDictName());
                    dataList.add(sendSalaryDataDto);
                }
            }
        }
        return dataList;
    }

    public static void main(String[] args) {

    }

}
